package com.shudai.largescreen.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.shudai.largescreen.mapper.PinCrownMapper;
import com.shudai.largescreen.pojo.dto.DeptDetailDto;
import com.shudai.largescreen.pojo.dto.UserDetailDto;
import com.shudai.largescreen.pojo.vo.DistributorVo;
import com.shudai.largescreen.pojo.vo.Region;
import com.shudai.largescreen.pojo.vo.TopSaleStaticVo;
import com.shudai.largescreen.service.PinCrownService;
import com.shudai.largescreen.util.DateQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class PinCrownServiceImpl implements PinCrownService {

    private final PinCrownMapper pinCrownMapper;

    @Override
    public List<TopSaleStaticVo> getTopSaleStatic() {

        //本周第一天
        String weekStart = DateQuery.getWeekStart();
//        String weekStart = "2022-05-10 00:00:00";

        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime localTime = LocalDateTime.parse(weekStart, df);

        //查询销售人员姓名，id和地址
        List<UserDetailDto> userDital = pinCrownMapper.findUserDital();

        //根据id 查询用户的本周总金额
//        List<Long> collect = userDital.stream().map(UserDetailDto::getId).collect(Collectors.toList()); 625
        List<Long> collect = new ArrayList<>();
        collect.add(Long.parseLong("625"));
        List<UserDetailDto> userDetileMoney = pinCrownMapper.findAllMoneyWeek(collect,localTime);

        //查询新增客户 本周
        List<UserDetailDto> customerNew = pinCrownMapper.findCustomerNew(collect, localTime);

        //查询总用户数
        List<UserDetailDto> allCustomer = pinCrownMapper.findAllCustomer(collect);


//        //查询最近七天下单人
        //本月第一天 上月第一天到上月最后一天
        LocalDateTime startM = LocalDateTime.parse(DateQuery.getMothStart(), df);

        LocalDateTime startMonth = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
        LocalDateTime endMonth = LocalDateTime.parse(DateQuery.getMothEndLast(), df);
        List<UserDetailDto> orderMothLast = pinCrownMapper.findOrderWeek(collect,startMonth,endMonth);

       if (CollectionUtils.isNotEmpty(orderMothLast)){
           //直接查
           List<Long> userRecordIds = orderMothLast.stream().map(UserDetailDto::getUserRecordId).collect(Collectors.toList());

           List<Long> userIds = orderMothLast.stream().map(UserDetailDto::getId).collect(Collectors.toList());
           //这个月 复购
           LocalDateTime startMothNow = LocalDateTime.parse(DateQuery.getMothStart(), df);
           List<UserDetailDto> userRate = pinCrownMapper.findUserRate(userRecordIds, startMothNow);

           //long userId  long 数量
           Map<Long, Long> userRateMap = userRate.stream().filter(x -> x.getTotal() > 0).collect(Collectors.groupingBy(UserDetailDto::getId, Collectors.counting()));

           //总订单 本月
           List<UserDetailDto> orderWeekTatal = pinCrownMapper.findOrderWeekTatal(userIds, startM);
            //long userId  long 数量
           Map<Long, Long> userTotalMap = orderWeekTatal.stream().filter(x -> x.getTotal() > 0).collect(Collectors.toMap(UserDetailDto::getId,UserDetailDto::getTotal));


           List<TopSaleStaticVo> topSaleStaticVos = new ArrayList<>();

           //本周下单用户id
//        pinCrownMapper.findAllUserRecordWeek(localTime);

           for (UserDetailDto userDetile : userDital) {
               TopSaleStaticVo topSaleStaticVo = new TopSaleStaticVo();
               topSaleStaticVo.setCustomerTotal(0);
               topSaleStaticVo.setCustomerNew("0");
               topSaleStaticVo.setTransactionAmount(0.00);
               topSaleStaticVo.setAvatarUrl("无");
               topSaleStaticVo.setId(userDetile.getId()+"");
               topSaleStaticVo.setOrderAmount("0");
               topSaleStaticVo.setRateReturn(new BigDecimal(0));
               topSaleStaticVo.setSalesman(userDetile.getUserName());
               topSaleStaticVo.setTeamName(userDetile.getProvince()+"-"+userDetile.getCity()+"-"+userDetile.getDistrict());

               //总金额
               for (UserDetailDto detile : userDetileMoney) {
                   if (userDetile.getId().equals(detile.getId())){
                       topSaleStaticVo.setTransactionAmount(detile.getOrderAmountWeek());
                   }
               }
               //新增用户数
               for (UserDetailDto detile : customerNew) {
                   if (userDetile.getId().equals(detile.getId())){
                       topSaleStaticVo.setCustomerNew(detile.getCustomerWeek());
                   }
               }
               //总用户数
               for (UserDetailDto detile : allCustomer) {
                   if (userDetile.getId().equals(detile.getId())){
                       topSaleStaticVo.setCustomerTotal(detile.getCustomerAll());
                   }
               }
               //返单
               Long rate = userRateMap.get(userDetile.getId());
               Long total = userTotalMap.get(userDetile.getId());
               System.out.println("rate:"+rate);
               System.out.println("total:"+total);

               if (total != null && rate != null){
                   topSaleStaticVo.setRateReturn(new BigDecimal(rate).divide(new BigDecimal(total),2,RoundingMode.HALF_UP));
               }
               System.out.println("setRateReturn:"+topSaleStaticVo.getRateReturn());
               topSaleStaticVos.add(topSaleStaticVo);
           }
           List<TopSaleStaticVo> collect1 = topSaleStaticVos.stream().sorted(Comparator.comparingDouble(TopSaleStaticVo::getTransactionAmount).reversed()).collect(Collectors.toList());

           for (int i = 0; i < collect1.size(); i++) {
               collect1.get(i).setTop((i+1));
           }
           return collect1;
       }else {
           List<TopSaleStaticVo> topSaleStaticVos = new ArrayList<>();

           //本周下单用户id
//        pinCrownMapper.findAllUserRecordWeek(localTime);

           for (UserDetailDto userDetile : userDital) {
               TopSaleStaticVo topSaleStaticVo = new TopSaleStaticVo();
               topSaleStaticVo.setCustomerTotal(0);
               topSaleStaticVo.setCustomerNew("0");
               topSaleStaticVo.setTransactionAmount(0.00);
               topSaleStaticVo.setAvatarUrl("无");
               topSaleStaticVo.setId(userDetile.getId()+"");
               topSaleStaticVo.setOrderAmount("0");
               topSaleStaticVo.setRateReturn(new BigDecimal(0));
               topSaleStaticVo.setSalesman(userDetile.getUserName());
               topSaleStaticVo.setTeamName(userDetile.getProvince()+"-"+userDetile.getCity()+"-"+userDetile.getDistrict());

               //总金额
               topSaleStaticVo.setTransactionAmount(0.00);

               //新增用户数
               topSaleStaticVo.setCustomerNew(0+"");

               //总用户数
               for (UserDetailDto detile : allCustomer) {
                   if (userDetile.getId().equals(detile.getId())){
                       topSaleStaticVo.setCustomerTotal(detile.getCustomerAll());
                   }
               }
               //返单
               topSaleStaticVo.setRateReturn(new BigDecimal(0));


               topSaleStaticVos.add(topSaleStaticVo);
           }
           List<TopSaleStaticVo> collect1 = topSaleStaticVos.stream().sorted(Comparator.comparingDouble(TopSaleStaticVo::getCustomerTotal).reversed()).collect(Collectors.toList());

           for (int i = 0; i < collect1.size(); i++) {
               collect1.get(i).setTop((i+1));
           }
           return collect1;
       }
    }


    @Override
    public List<DistributorVo> getTopDistributorStatic() {
        //本周第一天
        String weekStart = DateQuery.getWeekStart();
//        String weekStart = "2022-05-10 00:00:00";

        //1.具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//3.LocalDate发动，将字符串转换成  df格式的LocalDateTime对象，的功能
        LocalDateTime localTime = LocalDateTime.parse(weekStart, df);

        //查询部门id，名字，地址
        List<DeptDetailDto> deptDetail = pinCrownMapper.findDeptDetail();

        //查询本周总金额 部门id
        List<Long> collect = deptDetail.stream().map(DeptDetailDto::getId).collect(Collectors.toList());
        List<DeptDetailDto> allMoneyWeekDept = pinCrownMapper.findAllMoneyWeekDept(collect, localTime);

        //部门下的查询新增客户
        List<DeptDetailDto> customerNewDept = pinCrownMapper.findCustomerNewDept(collect, localTime);

        //查询总用户
        List<DeptDetailDto> allCustomerDept = pinCrownMapper.findAllCustomerDept(collect);

        LocalDateTime startM = LocalDateTime.parse(DateQuery.getMothStart(), df);
        LocalDateTime startMonth = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
        LocalDateTime endMonth = LocalDateTime.parse(DateQuery.getMothEndLast(), df);

        //查询部门下天下单用户
        List<DeptDetailDto> orderWeek = pinCrownMapper.findOrderWeekDept(collect,startMonth,endMonth);
       if (CollectionUtils.isNotEmpty(orderWeek)){
           List<Long> UserRecordIds = orderWeek.stream().map(DeptDetailDto::getUserRecordId).collect(Collectors.toList());
           List<DeptDetailDto> deptRate = pinCrownMapper.findUserRateDept(UserRecordIds,startM);

           // 返单数
           Map<Long, Long> deptRateMap = deptRate.stream().filter(x -> x.getTotal() > 0).collect(Collectors.groupingBy(DeptDetailDto::getId, Collectors.counting()));

           //查询这月
           List<Long> deptIds = orderWeek.stream().map(DeptDetailDto::getId).collect(Collectors.toList());
           List<DeptDetailDto> orderWeekTatolDept = pinCrownMapper.findOrderWeekTatolDept(deptIds, startM);
           Map<Long, Long> deptTotalMap = orderWeekTatolDept.stream().filter(x -> x.getTotal() > 0).collect(Collectors.toMap(DeptDetailDto::getId,DeptDetailDto::getTotal));


           List<DistributorVo> deptDetailDtos = new ArrayList<>();


           for (DeptDetailDto deptDetailDto : deptDetail) {
               DistributorVo distributorVo = new DistributorVo();
               distributorVo.setCustomerTotal(0);
               distributorVo.setCustomerNew("0");
               distributorVo.setTransactionAmount(0.00);
               distributorVo.setAvatarUrl("无");
               distributorVo.setId(deptDetailDto.getId()+"");
               distributorVo.setRateReturn(new BigDecimal(0));
               distributorVo.setSalesman(deptDetailDto.getDeptName());

//            distributorVo.setTeamName(deptDetailDto.getProvince()+"-"+deptDetailDto.getCity()+"-"+deptDetailDto.getDistrict());
               distributorVo.setTeamName(deptDetailDto.getDeptName());

               //查询本周总金额
//            deptDetailDto.getProvince().equals(detailDto.getProvince()) && deptDetailDto.getCity().equals(detailDto.getCity()) && deptDetailDto.getDistrict().equals(detailDto.getDistrict())
               for (DeptDetailDto detailDto : allMoneyWeekDept) {
                   if (deptDetailDto.getId().equals(detailDto.getId())){
                       distributorVo.setTransactionAmount(detailDto.getOrderAmountWeek());
                   }
               }
               //新增用户数
               for (DeptDetailDto detailDto : customerNewDept) {
                   if (deptDetailDto.getId().equals(detailDto.getId())){
                       distributorVo.setCustomerNew(detailDto.getCustomerWeek());
                   }
               }
               //总用户
               for (DeptDetailDto detailDto : allCustomerDept) {
                   if (deptDetailDto.getId().equals(detailDto.getId())){
                       distributorVo.setCustomerTotal(detailDto.getCustomerAll());
                   }
               }

               //返单
               Long rate = deptRateMap.get(deptDetailDto.getId());
               Long total = deptTotalMap.get(deptDetailDto.getId());
               if (total != null && rate != null){
                   distributorVo.setRateReturn(new BigDecimal(rate).divide(new BigDecimal(total),2,RoundingMode.HALF_UP));
               }

               deptDetailDtos.add(distributorVo);
           }
           List<DistributorVo> collect1 = deptDetailDtos.stream().sorted(Comparator.comparingDouble(DistributorVo::getTransactionAmount).reversed()).collect(Collectors.toList());

           for (int i = 0; i < collect1.size(); i++) {
               collect1.get(i).setTop((i+1));
           }
           return collect1;
       }else {
           List<DistributorVo> deptDetailDtos = new ArrayList<>();

           for (DeptDetailDto deptDetailDto : deptDetail) {
               DistributorVo distributorVo = new DistributorVo();
               distributorVo.setCustomerTotal(0);
               distributorVo.setCustomerNew("0");
               distributorVo.setTransactionAmount(0.00);
               distributorVo.setAvatarUrl("无");
               distributorVo.setId(deptDetailDto.getId()+"");
               distributorVo.setRateReturn(new BigDecimal(0));
               distributorVo.setSalesman(deptDetailDto.getDeptName());

//            distributorVo.setTeamName(deptDetailDto.getProvince()+"-"+deptDetailDto.getCity()+"-"+deptDetailDto.getDistrict());
               distributorVo.setTeamName(deptDetailDto.getDeptName());

               //查询本周总金额
//            deptDetailDto.getProvince().equals(detailDto.getProvince()) && deptDetailDto.getCity().equals(detailDto.getCity()) && deptDetailDto.getDistrict().equals(detailDto.getDistrict())
               distributorVo.setTransactionAmount(0.00);

               //新增用户数
               distributorVo.setCustomerNew(0+"");

               //总用户
               for (DeptDetailDto detailDto : allCustomerDept) {
                   if (deptDetailDto.getId().equals(detailDto.getId())){
                       distributorVo.setCustomerTotal(detailDto.getCustomerAll());
                   }
               }
               //返单
               distributorVo.setRateReturn(new BigDecimal(0));

               deptDetailDtos.add(distributorVo);
           }
           List<DistributorVo> collect1 = deptDetailDtos.stream().sorted(Comparator.comparingInt(DistributorVo::getCustomerTotal).reversed()).collect(Collectors.toList());

           for (int i = 0; i < collect1.size(); i++) {
               collect1.get(i).setTop((i+1));
           }
           return collect1;
       }

    }

    /**
     * 得到所有地区变树
     * @return
     */
    @Override
    public JSONArray getRegionalFiltering() {
        //数据库带有父子结构

        //返回格式
        JSONArray js = new JSONArray();
//1. 查库-列表如原型图所示
        List<Region> screenGuidanceList = pinCrownMapper.findAllCityTeam();


//分组保留原有顺序-(按BrandName分组，并保留其原有顺序)

        Map<String, List<Region>> lists = screenGuidanceList.stream().collect(Collectors.groupingBy(Region::getLabel, LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));

//遍历
        for (Map.Entry<String, List<Region>> entry : lists.entrySet()) {
            JSONObject brandObject = new JSONObject();
//            //获取list集合
            List<Region> value = entry.getValue();
//            //获取key值
            String keys = entry.getKey();

            brandObject.put("label", keys);
            brandObject.put("value", keys);
//
            JSONArray modelArray = new JSONArray();

            //Map<String, List<ScreenGuidanceVO>> modelList = value.stream().collect(Collectors.groupingBy(ScreenGuidanceVO::getModelName));--未保证其顺序
            //保持原有顺序-（LinkedHashMap按插曲顺序排序）
            Map<String, List<Region>> modelList = value.stream().collect(Collectors.groupingBy(Region::getValue, LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));

            for (Map.Entry<String, List<Region>> modelEntry : modelList.entrySet()) {
                JSONArray modelArray1 = new JSONArray();
                JSONObject modelObject = new JSONObject();
                //获取list集合
                List<Region> modelValue = modelEntry.getValue();

                //获取key值
                String modelKey = modelEntry.getKey();

//                modelObject.put("label", modelKey);
//                //获取中下游点字段的集合

                modelObject.put("value", modelKey);
                modelObject.put("label", modelKey);
                modelArray.add(modelObject);


//                List<String> downNo = modelValue.stream().map(Region::getTeam).distinct().collect(Collectors.toList());
                Map<String, List<Region>> downNo = modelValue.stream().collect(Collectors.groupingBy(Region::getTeam, LinkedHashMap::new, Collectors.toCollection(ArrayList::new)));

                for (Map.Entry<String, List<Region>> stringListEntry : downNo.entrySet()) {
                    JSONObject downNoObject = new JSONObject();
                    //获取list集合
                    List<Region> downNoValue = stringListEntry.getValue();

                    //获取key值
                    String downNoKey = stringListEntry.getKey();

                    System.out.println("key:");
                    for (int i = 0; i < downNoValue.size(); i++) {
                        System.out.println(downNoValue.get(i));
                    }
//                modelObject.put("label", modelKey);
//                //获取中下游点字段的集合

                    downNoObject.put("value", downNoKey);
                    downNoObject.put("label", downNoKey);
                    modelArray1.add(downNoObject);

                }
                modelObject.put("children", modelArray1);
            }
            brandObject.put("children", modelArray);


            js.add(brandObject);

        }
        System.out.println(js);

        return js;
    }


    @Override
    public List<Region> getSalesMan() {
        //这上上月 第一天和最后一天
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String mothStartLast = DateQuery.getMothStartLast2();
        LocalDateTime startMothLast = LocalDateTime.parse(mothStartLast, df);
        return pinCrownMapper.findSalesMan(startMothLast);

    }
}
